package cn.steel.controller.buyer;

import cn.steel.domain.entity.User;
import cn.steel.domain.vo.NotificationVo;
import cn.steel.domain.vo.ProductVo;
import cn.steel.service.BrowseHistoryService;
import cn.steel.service.FavoriteService;
import cn.steel.service.NotificationService;
import cn.steel.service.UserService;
import com.github.pagehelper.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@Slf4j
@Controller
@RequestMapping("/buyer/profile")
@Api(tags = "买家个人中心管理")
@PreAuthorize("hasAuthority('BUYER')")
@RequiredArgsConstructor
public class BuyerProfileController {

    private final UserService userService;
    private final FavoriteService favoriteService;
    private final NotificationService notificationService;
    private final BrowseHistoryService browseHistoryService;

    @ApiOperation("显示个人信息页面")
    @GetMapping
    public String profile(
            @SessionAttribute(value = "user", required = false) User user,
            Model model,
            RedirectAttributes redirectAttributes) {
        log.info("显示个人信息页面: user={}", user != null ? user.getId() : null);
        model.addAttribute("user", user);
        return "buyer/profile";
    }

    @ApiOperation("更新个人信息")
    @PostMapping
    public String updateProfile(
            @SessionAttribute(value = "user", required = false) User sessionUser,
            @Valid @ModelAttribute User user,
            BindingResult bindingResult,
            @RequestParam(value = "avatarFile", required = false) MultipartFile avatarFile,
            Model model) {
        log.info("更新个人信息: sessionUser={}", sessionUser != null ? sessionUser.getId() : null);
        if (bindingResult.hasErrors()) {
            model.addAttribute("user", user);
            model.addAttribute("error", bindingResult.getAllErrors().get(0).getDefaultMessage());
            return "buyer/profile";
        }
        try {
            user.setId(sessionUser.getId());
            userService.updateUserProfile(user, avatarFile);
            sessionUser.setUsername(user.getUsername());
            sessionUser.setEmail(user.getEmail());
            sessionUser.setPhone(user.getPhone());
            sessionUser.setCompany(user.getCompany());
            sessionUser.setAddress(user.getAddress());
            sessionUser.setAvatar(user.getAvatar());
            model.addAttribute("success", "个人信息更新成功");
        } catch (IllegalArgumentException e) {
            model.addAttribute("error", e.getMessage());
        }
        model.addAttribute("user", sessionUser);
        return "buyer/profile";
    }

    @ApiOperation("显示收藏夹页面")
    @GetMapping("/favorites")
    public String favorites(
            @SessionAttribute(value = "user", required = false) User user,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            Model model) {
        log.info("显示收藏夹页面: user={}, page={}, size={}", user != null ? user.getId() : null, page, size);
        Page<ProductVo> favorites = favoriteService.getFavoritesPaginated(user.getId(), page, size);
        model.addAttribute("favorites", favorites.getResult());
        model.addAttribute("totalPages", favorites.getPages());
        model.addAttribute("currentPage", favorites.getPageNum());
        model.addAttribute("pageSize", size);
        return "buyer/favorites";
    }

    @ApiOperation("移除收藏")
    @PostMapping("/favorites/remove/{id}")
    public String removeFavorite(@PathVariable Long id, RedirectAttributes redirectAttributes) {
        try {
            favoriteService.removeFavorite(id);
            redirectAttributes.addFlashAttribute("success", "已移除收藏");
        } catch (IllegalArgumentException e) {
            redirectAttributes.addFlashAttribute("error", e.getMessage());
        }
        return "redirect:/buyer/profile/favorites";
    }

    @ApiOperation("显示商品浏览历史页面")
    @GetMapping("/history")
    public String browseHistory(
            @SessionAttribute(value = "user", required = false) User user,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            Model model) {
        log.info("显示商品浏览历史页面: user={}, page={}, size={}", user != null ? user.getId() : null, page, size);
        Page<ProductVo> history = browseHistoryService.getBrowseHistoryPaginated(user.getId(), page, size);
        model.addAttribute("history", history.getResult());
        model.addAttribute("totalPages", history.getPages());
        model.addAttribute("currentPage", history.getPageNum());
        model.addAttribute("pageSize", size);
        return "buyer/history";
    }

    @ApiOperation("清除浏览历史")
    @PostMapping("/history/clear")
    public String clearHistory(
            @SessionAttribute(value = "user", required = false) User user) {
        log.info("清除浏览历史: user={}", user != null ? user.getId() : null);
        browseHistoryService.clearBrowseHistory(user.getId());
        return "redirect:/buyer/profile/history";
    }

    @ApiOperation("显示消息通知页面")
    @GetMapping("/notifications")
    public String notifications(
            @SessionAttribute(value = "user", required = false) User user,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            Model model) {
        log.info("显示消息通知页面: user={}, page={}, size={}", user != null ? user.getId() : null, page, size);
        Page<NotificationVo> notifications = notificationService.getNotificationsPaginated(user.getId(), page, size);
        model.addAttribute("notifications", notifications.getResult());
        model.addAttribute("totalPages", notifications.getPages());
        model.addAttribute("currentPage", notifications.getPageNum());
        model.addAttribute("pageSize", size);
        return "buyer/notifications";
    }

    @ApiOperation("标记通知为已读")
    @PostMapping("/notifications/read/{id}")
    public String markNotificationAsRead(
            @SessionAttribute(value = "user", required = false) User user,
            @PathVariable Long id) {
        log.info("标记通知为已读: user={}, notificationId={}", user != null ? user.getId() : null, id);
            notificationService.markAsRead(id, user.getId());
        return "redirect:/buyer/profile/notifications";
    }

    @ApiOperation("删除通知")
    @PostMapping("/notifications/delete/{id}")
    public String deleteNotification(
            @SessionAttribute(value = "user", required = false) User user,
            @PathVariable Long id) {
        log.info("删除通知: user={}, notificationId={}", user != null ? user.getId() : null, id);
            notificationService.deleteNotification(id, user.getId());
        return "redirect:/buyer/profile/notifications";
    }

    private String getStatusText(String status) {
        return switch (status) {
            case "PENDING" -> "待支付";
            case "PAID" -> "已支付";
            case "SHIPPED" -> "已发货";
            case "COMPLETED" -> "已完成";
            case "CANCELLED" -> "已取消";
            default -> "未知";
        };
    }

    @ApiOperation("显示修改密码页面")
    @GetMapping("/change_password")
    public String showChangePasswordForm(@SessionAttribute(value = "user", required = false) User user, Model model) {
           if (user == null){
               log.warn("用户未登录，跳转到登录页面");
               return "redirect:/login";
           }else {
               log.info("显示修改密码页面: userId={}", user.getId());
               model.addAttribute("userId", user.getId());
               return "buyer/change_password";
           }

    }

    @ApiOperation("修改密码")
    @PostMapping("/change_password")
    public String changePassword(
            @SessionAttribute(value = "user", required = false) User user,
            @RequestParam("oldPassword") String oldPassword,
            @RequestParam("newPassword") String newPassword,
            @RequestParam("confirmPassword") String confirmPassword,
            Model model) {
        if (user == null){
            log.warn("用户未登录，跳转到登录页面");
            return "redirect:/login";
        }
        log.info("修改密码: userId={}", user.getId());
        if (!newPassword.equals(confirmPassword)){
            model.addAttribute("error", "新密码和确认密码不一致");
            model.addAttribute("userId", user.getId());
            return "buyer/change_password";
        }
        try {
            userService.changePassword(user.getId(), oldPassword, newPassword);
            log.info("密码修改成功: userId={}", user.getId());
//            return "redirect:/buyer/profile?success=true";
            model.addAttribute("success", "密码修改成功");
        }catch (IllegalArgumentException e){
            log.error("密码修改失败: userId={}, error={}", user.getId(), e.getMessage());
            model.addAttribute("error", e.getMessage());
            model.addAttribute("userId", user.getId());
            return "buyer/change_password";
        }catch (Exception e){
            log.error("系统异常: userId={}, 错误信息={}", user.getId(), e.getMessage());
            model.addAttribute("error", "系统错误，请稍后再试");
            model.addAttribute("userId", user.getId());
            return "buyer/change_password";
        }
        return "buyer/change_password";
    }

}